package work.sajor.wechatpush.util;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class WechatUtils {
    @Value("${wechat.interface.config.token}")
    private String token;
    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.secret}")
    private String appsecret;
    private static String secretId;
    private static String secretKey;
    private static String tokens;

    public static String getToken() { return tokens; }
    public static String getSecretId() {return secretId;}
    public static String getSecretKey() {return secretKey;}

    /**
     * 调用微信接口
     */
    private WxMpService wxMpService;

    /**
     * 初始化
     */
    @PostConstruct
    private void init() {
        secretId = this.appid;
        secretKey = this.appsecret;
        tokens=this.token;
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(appid);
        wxMpConfigStorage.setSecret(appsecret);
        wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
    }

    /**
     * 获取 access_token 不刷新
     * @return access_token
     * @throws WxErrorException
     */
    public String getAccessToken() throws WxErrorException {
        return wxMpService.getAccessToken();
    }


    public WxMpUserList getUserList() throws WxErrorException {
        return wxMpService.getUserService().userList(null);
    }

    public WxMpUser getUserInfo(String openId) throws WxErrorException {
        return wxMpService.getUserService().userInfo(openId);
    }
}